var async = require('async');
var util = require("util");

var BaseApi = require('./baseApi').BaseApi;

exports.CommonApi = (function() {
    function CommonApi(mongoDB, keyValueStore, sessionStore) {
        this.mongoDB = mongoDB;
        this.keyValueStore = keyValueStore;
        this.sessionStore = sessionStore;
    }

    util.inherits(CommonApi, BaseApi);

    //보낸 메시지, 받은 메시지 얻기
    CommonApi.method("getMessageInfo", function(req, res)
    {
        var _self = this;

        async.waterfall([
                    function(callback) {
                        /*$or : [{"From": req.session.user},{"To":  req.session.user}]}*/
                        _self.mongoDB.db.collection("Message").find({"From": req.session.user}).toArray(function(err,fromUser)
                        {
                           /* result.forEach(function(item) { });*/
                            callback(err, fromUser);
                        });
                    },
                    function(fromUser, callback)
                    {
                        _self.mongoDB.db.collection("Message").find({"To" : req.session.user}).toArray(function(err,toUser)
                        {
                            callback(err, fromUser, toUser);
                        });
                    }
        ], function(err, fromUser,toUser )
            {
                 res.send({fromUser : fromUser,toUse : toUser});
            }
        );

    });

    //메시지 전송
    CommonApi.method("sendMessage", function(req, res)
    {
        var _self = this;
        req.body.sendDate = new Date();

        _self.mongoDB.db.collection("Message").insert(req.body, function (err, result) {
                    res.send("ok");
        });


    });

    //받은 메시지 카운터 가져오기
    CommonApi.method("getMessageCount", function(req, res)
    {
        var _self  = this;
        _self.mongoDB.db.collection("Message").find({"To": "pjy1" }).count;
    });

    //메시지 삭제
    CommonApi.method("deleteMessage", function(req, res)
    {
        var _self = this


    });

    return CommonApi;
})();
